//
//  HomeAction.swift
//  home
//
//  Created by Yun Zeng on 2018/11/28.
//  Copyright © 2018 Yun Zeng. All rights reserved.
//

import Foundation

// 工作
// 用户操作、场景、自动化的执行任务的基本单元
class HomeAction: Codable {
    var aid: String
    var sid: Int
    var cid: Int
    var value: AnyJSONType
    
    // 根据Characteristic创建一个动作
    init?<T>(characteristic: HMCharacteristic, targetValue: T) where T: JSONType {
        guard let accessory = characteristic.service?.accessory else {
            return nil
        }
        guard let service = characteristic.service else {
            return nil
        }
        self.aid = accessory.id
        self.sid = service.id
        self.cid = characteristic.id
        self.value = AnyJSONType(targetValue)
    }
}

// 通过通常会作为一个集合(Set)使用
extension HomeAction: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(self.aid)
        hasher.combine(self.sid)
        hasher.combine(self.cid)
    }
    
    static func == (lhs: HomeAction, rhs: HomeAction) -> Bool {
        if lhs.aid == rhs.aid && lhs.sid == rhs.sid && lhs.cid == rhs.cid {
            return true
        }
        return false
    }
}

// 日志打印
extension HomeAction: CustomStringConvertible {
    var description: String {
        let data = try! JSONEncoder().encode(self)
        return String(data: data, encoding: .utf8)!
    }
}








